package com.jjlin.chapter_5;

import java.util.*;
public class CD122{

    //数组中两个字符串的最小距离
    public static int minDistance(String[] s, String s1, String s2){
        if(s1 == null || s2 == null)
            return -1;
        if(s1.equals(s2))
            return 0;
        int min = Integer.MAX_VALUE;
        int last1 = -1, last2 = -1; //标记s1和s2在数组中最新出现的位置
        for(int i = 0; i < s.length; i++){
            if(s[i].equals(s1)){
                min = Math.min(min, last2 == -1 ? min : i - last2); //只有last1和last2都不为-1才会更新min
                last1 = i; //更新last1
            }
            if(s[i].equals(s2)){
                min = Math.min(min, last1 == -1 ? min : i - last1);
                last2 = i; //更新last2
            }
        }

        return min == Integer.MAX_VALUE ? -1 : min;
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String s1 = sc.next();
        String s2 = sc.next(); //注意next()并没有读取换行符，因此后面需要sc.nextLine()
        sc.nextLine();
        String[] s = new String[n];
        for(int i = 0; i < n; i++){
            s[i] = sc.nextLine();
        }
        System.out.println(minDistance(s, s1, s2));
    }
}
